import { addEntity, addComponent, hasComponent, type IWorld, type Entity } from '$lib/ecs';
import { decode, encode } from './util';
import { Null, Feature, Creature, Name, Description } from './components';
import { Item } from './item';
import { Ground } from './content/ground';
import { Clock, clockOnlyQuery, Global } from './clock';

export const nullEntity = 0;

export const describe = (world: IWorld, e: Entity) => {
  if (hasComponent(world, Name, e)) {
    return decode(Name.name[e]);
  } else if (hasComponent(world, Description, e)) {
    return decode(Description.summary[e]);
  }
  return '<unknown>';
};

export const describeStack = (world, stack) => {
  let floor = [];
  let feature = [];
  let items = [];
  let creature = [];
  for (let e of stack) {
    const dsc = describe(world, e);
    if (hasComponent(world, Ground, e)) {
      floor = [dsc];
    } else if (hasComponent(world, Feature, e)) {
      feature = [dsc];
    } else if (hasComponent(world, Creature, e)) {
      creature = [dsc];
    } else if (hasComponent(world, Item, e)) {
      items.push(dsc);
    }
  }
  return [...floor, ...feature, ...items, ...creature].join(', ');
};

export const getTime = (world) => {
  return Clock.time[clockOnlyQuery(world)[0]];
};

export const createNullEntity = (world) => {
  const e = addEntity(world);
  if (e !== nullEntity)
    throw new Error('Null entity != 0');
  addComponent(world, Null, e);
};

export const createClock = (world) => {
  const e = addEntity(world);
  addComponent(world, Clock, e);
  addComponent(world, Global, e);
  Clock.created[e] = 0;
  Clock.time[e] = 0;
};
